package com.atguigu.tingshu.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import io.lettuce.core.dynamic.annotation.Key;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * projectName: tingshu-parent
 *
 * @author: 王宝贵
 * time: 2024/11/1 21:02 周五
 * description:
 */
@Slf4j
@Component
public class AlbumReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true",autoDelete = "false"),
            exchange =@Exchange(value = MqConst.EXCHANGE_TRACK),
            key ={MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    @SneakyThrows
    public void updateTrackStat(String mes, Message message, Channel channel){
         if(mes==null){
             return ;
         }
       /* TrackStatMqVo  trackStatMqVo =(TrackStatMqVo) JSON.parse(mes);*/
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(mes, TrackStatMqVo.class);

        String key= RedisConstant.BUSINESSNO+trackStatMqVo.getBusinessNo();

        try {
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, trackStatMqVo.getTrackId(), 1, TimeUnit.HOURS);
            if(flag){
                trackInfoService.updateTrackStat(trackStatMqVo);
            }

            //确认消息 --不放回队列
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            //消息返回队列
            redisTemplate.delete(key);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }


    }

}